package com.mav01.mrpbackend.controller;

import com.mav01.mrpbackend.pojo.Debt;
import com.mav01.mrpbackend.pojo.Result;
import com.mav01.mrpbackend.service.DebtService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/debt")
public class DebtController {

    @Autowired
    private DebtService debtService;

    // 根据变量名查询行数据 - GET
    @GetMapping("/variable/{variableName}")
    public Result<Debt> selectByVariable(@PathVariable String variableName) {
        Debt debt = debtService.selectByVariable(variableName);
        if (debt != null) {
            return Result.success(debt);
        } else {
            return Result.error("未找到该变量名对应的数据");
        }
    }

    // 查询全部数据 - GET
    @GetMapping("/all")
    public Result<List<Debt>> selectAll() {
        List<Debt> debts = debtService.selectAll();
        return Result.success(debts);
    }

    // 根据id修改一条数据 - UPDATE
    @PutMapping("/update")
    public Result<String> update(@RequestBody Debt debt) {
        int result = debtService.update(debt);
        if (result > 0) {
            return Result.success("更新成功");
        } else {
            return Result.error("更新失败");
        }
    }

    // 插入一条数据 - POST
    @PostMapping("/insert")
    public Result<String> insert(@RequestBody Debt debt) {
        int result = debtService.insert(debt);
        if (result > 0) {
            return Result.success("插入成功");
        } else {
            return Result.error("插入失败");
        }
    }

    // 根据变量名删除一条数据 - DELETE
    @DeleteMapping("/variable/{variableName}")
    public Result<String> deleteByVariable(@PathVariable String variableName) {
        int result = debtService.deleteByVariable(variableName);
        if (result > 0) {
            return Result.success("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    // 计算汇总 - post
    @PostMapping ("/calculate")
    public Result<String> calculate(@RequestBody Debt debt) {
        try {
            String formula = debtService.calculate(debt);
            return Result.success(formula);
        } catch (RuntimeException e) {
            return Result.error("计算失败: " + e.getMessage());
        }
    }
}